import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

public class Server {
    public static void main(String [] args) throws EOFException {
        String fileName = "pulse_data_" + String.valueOf(System.currentTimeMillis()) + ".csv";
        System.out.println("服务器运行...");
        Thread thread = new Thread(() -> {//这是lambda表达式，写在线程方法中非常方便

            try (
                    ServerSocket serverSocket = new ServerSocket(8888);
                    Socket socket = serverSocket.accept();

                    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                    DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            ) {
                while (true) {
                    String iString = inputStream.readUTF();//读取信息要放在最前面，以读取客户端发来的信息
//                    String aString = bufferedReader.readLine();

                    // 将收到的数据存入文件中
                    PulseData pld = new PulseData();

                    if((iString != "") && (iString != null)) {
                        if(iString.length() > 1) {
                            String json_str = iString.substring(1, iString.length() - 1);
                            String[] item = json_str.split(",");
                            HashMap<String, Integer> data = new HashMap<String, Integer>();

                            for(int i = 0; i < item.length; i++) {
                                String[] kv = item[i].split(":");

                                if(kv.length == 2) {
                                    data.put(kv[0], Integer.parseInt(kv[1]));
                                    System.out.println(iString + " 已收到并保存！");
                                }
                            }

                            pld.writePatientSendData("F:\\IDEA_project\\ComNetTele\\src\\pulse_data\\" + fileName, data);

                            //写入输出流
                            String aString = "已收到！";
                            outputStream.writeUTF(aString);
                            //将输出流刷新
                            outputStream.flush();
                        }
                    }
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("服务器停止");
        });
        thread.start();
    }
}
